<template>
  <div class="table-wrap">
    <div class="form-header">
      <el-form :inline="true" :model="formInline" class="demo-form-inline">
        <el-form-item label="">
          <el-select
            v-model="formInline.status"
            class="m-2"
            clearable
            placeholder="筛选"
          >
            <el-option label="草稿" value="0" />
            <el-option label="待审核" value="1" />
            <el-option label="已上架" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="">
          <el-input
            v-model="formInline.user"
            placeholder="输入名称/编号/其他搜索"
            clearable
          />
        </el-form-item>
        <el-form-item label="">
          <el-input
            v-model="formInline.region"
            placeholder="输入材料商名称搜索"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">查询</el-button>
          <el-button type="primary" @click="handleAdd">新增材料商</el-button>
          <el-button type="warning">批量删除</el-button>
        </el-form-item>
      </el-form>
      <div class="operate-btn-wrap">
        <el-button type="primary">类别筛选</el-button>
        <el-button type="primary">批量导入</el-button>
        <el-button type="primary">导出Excel</el-button>
      </div>
    </div>
    <el-table
      ref="multipleTableRef"
      :data="tableData"
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column label="邀请" width="100">
        <template #default="scope">
          <el-button @click="copyLink(scope.row)" type="primary" link
            >复制链接</el-button
          >
        </template>
      </el-table-column>
      <el-table-column type="selection" width="55" />
      <el-table-column type="index" label="序号" width="55">
        <template #default="scope">
          {{ getIndex(scope.$index) }}
        </template>
      </el-table-column>

      <el-table-column
        v-for="item in tableHeader"
        :key="item"
        :prop="item.prop"
        :label="item.name"
      >
        <template #default="scope">
          <img
            v-if="item.type == 'uploadImg'"
            :src="scope.row[item.prop]"
            style="width: 80px; height: 60px"
            alt=""
          />
          <div v-if="item.prop == 'status'">
            <span v-if="scope.row[item.prop]">{{
              statusDesc(scope.row[item.prop])
            }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="250">
        <template #default="scope">
          <el-button @click="copyRow(scope.row)" link type="primary"
            >复制</el-button
          >
          <el-button @click="handleEdit(scope.row)" link type="primary"
            >编辑</el-button
          >
          <el-button
            v-if="scope.row.status == 0 || scope.row.status == 3"
            @click="handleSubmit(scope.row)"
            link
            type="primary"
            >提交</el-button
          >
          <el-button
            v-if="scope.row.status == 2 || scope.row.status == 5"
            @click="handlePutOnByAdmin(scope.row)"
            link
            type="primary"
            >上架</el-button
          >
          <el-button
            v-if="scope.row.status == 4"
            @click="handlePutOff(scope.row)"
            link
            type="primary"
            >下架</el-button
          >
          <el-button
            v-if="scope.row.status == 1"
            @click="handleExamine(scope.row)"
            link
            type="primary"
            >审核</el-button
          >
          <el-button
            v-if="scope.row.status == 0"
            @click="handleDelete(scope.row)"
            link
            type="primary"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="30%"
      align-center
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="120px"
        class="demo-ruleForm"
        status-icon
      >
        <template v-for="item in tableHeader" :key="item">
          <el-form-item
            v-if="!item.hidden"
            :label="item.name"
            :prop="item.prop"
          >
            <el-select
              v-if="item.type == 'select'"
              :multiple="item.multi ? true : false"
              v-model="ruleForm[item.prop]"
              placeholder=""
            >
              <el-option label="住宅" value="0" />
              <el-option label="公寓" value="1" />
            </el-select>
            <el-input
              v-if="item.type == 'input'"
              placeholder="请输入"
              v-model="ruleForm[item.prop]"
            ></el-input>
            <el-input
              v-if="item.type == 'textarea'"
              type="textarea"
              placeholder="请输入"
              v-model="ruleForm[item.prop]"
            ></el-input>
            <!-- <el-upload
              v-if="item.type == 'uploadImg'"
              v-model:file-list="fileList"
              class="upload-demo"
              action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
            >
              <el-button type="primary">上传图片</el-button>
            </el-upload> -->
            <!-- multiple 属性 可以实现多选的功能  -->
            <input
              type="file"
              v-if="item.type == 'uploadImg'"
              v-on:change="uploadFile"
            />
            <!-- <input
              id="file"
              v-if="item.type == 'uploadImg'"
              class="filepath"
              multiple
              ref="upload_video"
              accept=""
              @change="changeVideo($event)"
              type="file"
            /> -->

            <NumberRange
              :value="ruleForm[item.prop]"
              v-if="item.type == 'numberRange'"
            ></NumberRange>
            <!-- <div v-if="item.type == 'text'">{{ ruleForm[item.prop] }}</div> -->
          </el-form-item>
        </template>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmForm"> 确认 </el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog
      v-model="centerDialogVisible"
      title="邀请链接"
      width="60%"
      align-center
    >
      <div :class="copyLinkActive ? 'active' : ''" class="link-content">
        {{ copyLinkValue }}
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="centerDialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="confirmCopy"> 复制 </el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog width="600px" v-model="outerVisible" title="拒绝审核">
      <el-input v-model="reason" placeholder="请输入原因"></el-input>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="outerVisible = false">取消</el-button>
          <el-button type="primary" @click="rejectHanldle"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { ref, reactive, computed } from "vue";
import * as qiniu from "qiniu-js";
import SparkMD5 from "spark-md5";
import NumberRange from "@/components/InputNumberRange";
import {
  getMaterialSupplierInfos,
  addMaterialSupplierInfo,
  modifyMaterialSupplierInfo,
  deleteMaterialSupplierInfo,
  getGenerateInvitationCode,
  putOnMaterialSupplierInfo,
  putOnMaterialSupplierInfoByAdmin,
  examineMaterialSupplierInfo,
  putOffMaterialSupplierInfo,
  submitMaterialSupplierInfo,
} from "@/api/material";
import { getInitMultipartUploadWithPublic } from "@/api/login";
import { getFilesUrl, copyDomText } from "@/utils/index";
import { ElMessage, ElMessageBox } from "element-plus";
const formInline = reactive({
  user: "",
  region: "",
  status: "",
});
const outerVisible = ref(false);
const reason = ref("");
// 状态（0：草稿，1：待审核，2：待上架，3：审核不通过，4:已上架，5：已下架）
const statusDesc = (status) => {
  let temp = "";
  switch (status) {
    case "0":
      temp = "草稿";
      break;
    case "1":
      temp = "待审核";
      break;
    case "2":
      temp = "待上架";
      break;
    case "3":
      temp = "审核不通过";
      break;
    case "4":
      temp = "已上架";
      break;
    case "5":
      temp = "已下架";
      break;

    default:
      temp = "";
      break;
  }
  return temp;
};
const multipleTableRef = ref();
const multipleSelection = ref([]);
const toggleSelection = (rows) => {
  if (rows) {
    rows.forEach((row) => {
      multipleTableRef.value.toggleRowSelection(row);
    });
  } else {
    multipleTableRef.value.clearSelection();
  }
};
const handleSelectionChange = (val) => {
  multipleSelection.value = val;
};
const currentPage = ref(1);
const pageSize = ref(10);
const tableHeader = [
  { prop: "businessPremises", name: "封面", type: "uploadImg" },
  { prop: "materialSupplierName", name: "材料商名称", type: "input" },
  { prop: "introductionInfo", name: "介绍信息", type: "textarea" },
  { prop: "serviceArea", name: "服务区域", type: "input" },
  { prop: "contactInfo", name: "联系方式", type: "input" },
  { prop: "mainMaterials", name: "主营材料", type: "input" },
  { prop: "commodityInfoCount", name: "商品数", type: "text", hidden: true },
  {
    prop: "commodityInfoExampleCount",
    name: "提供样品数",
    type: "text",
    hidden: true,
  },
  { prop: "status", name: "状态", type: "text", hidden: true },
  //   { prop: "time", name: "创建时间", hidden: true },
];
const getIndex = (index) => {
  return (currentPage.value - 1) * pageSize.value + index + 1;
};

const uploadFile = async (event) => {
  let md5 = "";
  const file = event.target.files[0];
  const sparkMD5 = new SparkMD5();
  const reader = new FileReader();
  reader.readAsText(file);
  reader.onload = async (event) => {
    //获取文件MD5
    const str = event.target.result;
    sparkMD5.append(str);
    md5 = sparkMD5.end();

    const res = await getInitMultipartUploadWithPublic(md5);
    // 生成随机文件名，防止文件名冲突
    const key = Date.now().toString() + file.name;
    console.log("获取文件MD5", res);
    const token = res.result.upToken;
    let config = {
      //存储区域(z0:代表华东;z2:代表华南,不写默认自动识别)
      // region: qiniu.region.z2,
      //分片上传的并发请求量
      concurrentRequestLimit: 2,
    };

    // 使用七牛的upload方法上传文件
    const observable = qiniu.upload(file, key, token, config, {});

    // 订阅上传进度事件
    observable.subscribe({
      next(res) {
        console.log(res.total);
      },
      error(err) {
        console.error(err);
      },
      complete(res) {
        console.log(res);
      },
    });
  };
};

const getListData = async () => {
  const params = {
    pageId: 1,
    pageSize: 20,
    count: false,
    status: formInline.status,
  };
  try {
    const res = await getMaterialSupplierInfos(params);
    if (res.code == 200) {
      const temp =
        res.result.list.map(async (x) => {
          let businessPremises = "";
          if (x.businessPremises != "") {
            const res1 = await getFilesUrl(x.businessPremises);

            businessPremises = res1;
            return {
              ...x,
              businessPremises,
            };
          }

          return {
            ...x,
          };
        }) || [];
      const result = await Promise.all(temp);

      tableData.value = result;
    }
  } catch (error) {
    console.log("error", error);
  }
};
getListData();
const onSubmit = () => {
  getListData();
};
const ruleForm = reactive({
  businessPremises: "",
  materialSupplierName: "",
  introductionInfo: "",
  serviceArea: "",
  contactInfo: "",
  mainMaterials: "",
});
const dialogTitle = ref("添加材料商");
const dialogType = ref("add");
const dialogVisible = ref(false);
const centerDialogVisible = ref(false);
const copyLinkValue = ref("");
const currentRow = ref();
const copyLinkActive = ref(false);
const handleEdit = (item) => {
  console.log("item", item);
  dialogTitle.value = "编辑材料商";
  dialogType.value = "edit";
  currentRow.value = item;
  dialogVisible.value = true;
  nextTick(() => {
    ruleForm.businessPremises = item.businessPremises;
    ruleForm.materialSupplierName = item.materialSupplierName;
    ruleForm.introductionInfo = item.introductionInfo;
    ruleForm.serviceArea = item.serviceArea;
    ruleForm.contactInfo = item.contactInfo;
    ruleForm.mainMaterials = item.mainMaterials;
    ruleForm.commodityInfoCount = item.commodityInfoCount;
    ruleForm.commodityInfoExampleCount = item.commodityInfoExampleCount;
  });
};
const handleListing = (item) => {};
const copyLink = async (item) => {
  centerDialogVisible.value = true;

  try {
    const res = await getGenerateInvitationCode({
      materialSupplierInfoId: item.materialSupplierInfoId,
    });
    if (res.code == 200) {
      copyLinkValue.value = res.result || "";
    }
  } catch (error) {}
  copyLinkActive.value = false;
};
const confirmCopy = () => {
  copyLinkActive.value = true;
  copyDomText(copyLinkValue.value);
};
const handlePutOn = (item) => {
  ElMessageBox.confirm("确定上架么?", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      const res = await putOnMaterialSupplierInfo([
        item.materialSupplierInfoId,
      ]);
      if (res.code == 200) {
        ElMessage({
          type: "success",
          message: "上架成功",
        });
        getListData();
      }
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消",
      });
    });
};
const handlePutOnByAdmin = (item) => {
  ElMessageBox.confirm("确定上架么?", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      const res = await putOnMaterialSupplierInfoByAdmin([
        item.materialSupplierInfoId,
      ]);
      if (res.code == 200) {
        ElMessage({
          type: "success",
          message: "上架成功",
        });
        getListData();
      }
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消",
      });
    });
};
const handleSubmit = (item) => {
  ElMessageBox.confirm("确定提交么?", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      const res = await submitMaterialSupplierInfo([
        item.materialSupplierInfoId,
      ]);
      // const res = await submitMaterialSupplierInfo({
      //   materialSupplierInfoIds: item.materialSupplierInfoId,
      // });
      if (res.code == 200) {
        ElMessage({
          type: "success",
          message: "提交成功",
        });
        getListData();
      }
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消",
      });
    });
};
const handleExamine = (item) => {
  currentRow.value = item;
  ElMessageBox.confirm("确定审核么?", "提示", {
    confirmButtonText: "通过",
    cancelButtonText: "拒绝",
    type: "warning",
  })
    .then(async () => {
      const res = await examineMaterialSupplierInfo({
        materialSupplierInfoIds: [item.materialSupplierInfoId],
        isPass: true,
      });
      if (res.code == 200) {
        ElMessage({
          type: "success",
          message: "审核成功",
        });
        getListData();
      }
    })
    .catch(() => {
      outerVisible.value = true;
    });
};
const rejectHanldle = async () => {
  if (reason.value == "") {
    return ElMessage({
      type: "warning",
      message: "请输入原因",
    });
  }
  try {
    const res = await examineMaterialSupplierInfo({
      isPass: false,
      reason: reason.value,
      materialSupplierInfoIds: [currentRow.value.materialSupplierInfoId],
    });
    if (res.code == 200) {
      ElMessage({
        type: "success",
        message: "审核不通过",
      });
      getListData();
      outerVisible.value = false;
    }
  } catch (error) {}
};
const handlePutOff = (item) => {
  ElMessageBox.confirm("确定下架么?", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      const res = await putOffMaterialSupplierInfo([
        item.materialSupplierInfoId,
      ]);
      if (res.code == 200) {
        ElMessage({
          type: "success",
          message: "下架成功",
        });
        getListData();
      }
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消",
      });
    });
};
const handleDelete = (item) => {
  ElMessageBox.confirm("确认删除此材料商信息?", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      const res = await deleteMaterialSupplierInfo({
        materialSupplierInfoId: item.materialSupplierInfoId,
        recordVersion: item.recordVersion,
      });
      if (res.code == 200) {
        ElMessage({
          type: "success",
          message: "删除成功",
        });
        getListData();
      }
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除",
      });
    });
};
const copyRow = (item) => {
  ElMessage({
    type: "success",
    message: "复制成功",
  });
  currentRow.value = item;
  setTimeout(() => {
    dialogTitle.value = "添加材料商";
    dialogType.value = "add";
    dialogVisible.value = true;
    nextTick(() => {
      ruleForm.businessPremises = item.businessPremises;
      ruleForm.materialSupplierName = item.materialSupplierName;
      ruleForm.introductionInfo = item.introductionInfo;
      ruleForm.serviceArea = item.serviceArea;
      ruleForm.contactInfo = item.contactInfo;
      ruleForm.mainMaterials = item.mainMaterials;
      ruleForm.commodityInfoCount = item.commodityInfoCount;
      ruleForm.commodityInfoExampleCount = item.commodityInfoExampleCount;
    });
  }, 500);
};
const ruleFormRef = ref();
const handleAdd = () => {
  dialogTitle.value = "添加材料商";
  dialogType.value = "add";
  dialogVisible.value = true;
  currentRow.value = {};
  nextTick(() => {
    ruleFormRef.value.resetFields();
  });
};
const tableData = ref([]);
const rules = reactive({
  name: [
    { required: true, message: "Please input Activity name", trigger: "blur" },
    { min: 3, max: 5, message: "Length should be 3 to 5", trigger: "blur" },
  ],
  region: [
    {
      required: true,
      message: "Please select Activity zone",
      trigger: "change",
    },
  ],
  count: [
    {
      required: true,
      message: "Please select Activity count",
      trigger: "change",
    },
  ],
  date1: [
    {
      type: "date",
      required: true,
      message: "Please pick a date",
      trigger: "change",
    },
  ],
  date2: [
    {
      type: "date",
      required: true,
      message: "Please pick a time",
      trigger: "change",
    },
  ],
  type: [
    {
      type: "array",
      required: true,
      message: "Please select at least one activity type",
      trigger: "change",
    },
  ],
  resource: [
    {
      required: true,
      message: "Please select activity resource",
      trigger: "change",
    },
  ],
  desc: [
    { required: true, message: "Please input activity form", trigger: "blur" },
  ],
});
const confirmForm = async () => {
  console.log("confirmForm", ruleForm);
  try {
    if (dialogType.value == "add") {
      const res = await addMaterialSupplierInfo(ruleForm);
      if (res.code == 200) {
        ElMessage({
          type: "success",
          message: "添加成功",
        });
        dialogVisible.value = false;
        getListData();
      }
    } else {
      const temp = {
        ...ruleForm,
        materialSupplierCode: currentRow.value.materialSupplierCode,
        materialSupplierInfoId: currentRow.value.materialSupplierInfoId,
        recordVersion: currentRow.value.recordVersion,
        status: currentRow.value.status,
      };
      const res = await modifyMaterialSupplierInfo(temp);
      if (res.code == 200) {
        ElMessage({
          type: "success",
          message: "编辑成功",
        });
        dialogVisible.value = false;
        getListData();
      }
    }
  } catch (error) {}
};
</script>
<style lang="scss" scoped>
.table-wrap {
  padding: 20px;
  .form-header {
    display: flex;
    justify-content: space-between;
  }
}
.demo-ruleForm {
  width: 100%;
  .el-select {
    width: 100%;
  }
}
.link-content {
  height: 80px;
  padding: 10px 20px;
  background: #fff;
  border: 1px solid #e0e0e0;
  border-radius: 5px;
  &.active {
    background: #cff4df;
    border-color: #cff4df;
  }
}
</style>
